from flask import Flask,request,render_template,redirect,url_for,jsonify
import json
import pymysql
from server_conf import *

app=Flask(__name__)

@app.route("/")
def root():
    class_id=0
    class_name=""
    with create_database_conn() as conn:
        with conn.cursor() as cursor:
            cursor.execute("select * from t_class where id=1")
            (class_id,class_name)=cursor.fetchone()
            print(class_name)

    return render_template('index.html',class_name=class_name)

@app.route('/api/zuowei')
def zuoweiJson():
    resData=None
    with create_database_conn() as conn:
        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            cursor.execute("select * from t_class_zuowei")
            resData=cursor.fetchall()

    return json.dumps(resData)

@app.route('/about')
def about():
    return 'This is the About page.'


@app.route('/wenhou', methods=['GET', 'POST'])
def greet():
    if request.method == 'POST':
        name = request.form['name']
    else:
        name = request.args.get('name', '你没有传，我只能给你默认值')
    return '你好, ' + name + '!'


@app.route('/welcome')
def welcome():
    if request.method == 'POST':
        name = request.form['name']
    else:
        name = request.args.get('name', '默认值')
    return render_template('index.html', name=name)


@app.route('/login')
def login():
    return render_template('login.html')

##创建数据库链接的方法
def create_database_conn():
    conn=pymysql.connect(host=mysql_info["ipaddress"],
                         user=mysql_info["usr"],
                         password=mysql_info["pwd"],
                         database=mysql_info["base"],
                         port=mysql_info["port"],
                         charset=mysql_info["charset"])
    return conn

##执行查询数据库表里的用户名密码
def queryUseranmePassword(conn,username,password):
    result=False

    cursor=conn.cursor()
    query_sql="select * from user where user_name='%s' and user_pwd='%s'" % (username,password)
    datas=cursor.execute(query_sql)
    if(datas>0):
        result=True
    cursor.close()
    return result

def checkUsernameAndPassword(username,password):
    ##查数据库表里是否匹配正确的用户名密码
    ##1. 连接数据库
    conn=create_database_conn()

    ##2.查询表并判断是否存在对应在用户名密码
    queryResult=queryUseranmePassword(conn,username,password)
    
    ##3.断开链接
    conn.close()
    return queryResult

@app.route('/doLogin',methods=['GET', 'POST'])
def doLogin():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        if(checkUsernameAndPassword(username,password)):
            return redirect(url_for('welcome'))
        else:
            err="用户名密码错误"
            return redirect(url_for('login'))
    else:
        err="提交方式错误"
        return redirect(url_for('login'))
    


if __name__ == '__main__':
    app.run(host="0.0.0.0",port=88,debug=True)
